package com.study.创造型模式.原型模式.深拷贝;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

import java.io.*;

public class DeepProtoType implements Serializable,Cloneable {

    public String name;  //String 属性
    public DeepCloneableTarget deepCloneableTarget; //引用类型

    public DeepProtoType() {
    }

    //深拷贝-    方式一：使用clone方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        deep = super.clone();  //这里完成对基本数据类型和字符串的克隆
        //对引用类型的属性，进行单独处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
        return deepProtoType;
    }

    //深拷贝 -    方式二：通过序列化(推荐使用)
    public Object deepClone(){
        //创建流对象
        ByteArrayInputStream bis = null;
        ByteArrayOutputStream bos = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;

        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);  //把当前这个对象序列化输出

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType copy = (DeepProtoType) ois.readObject();

            return copy;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                //关闭流
                //ByteArrayInputStream和ByteArrayOutputStream会自动关闭
                ois.close();
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
